package com.kabigon.tiny.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author xu.biao
 * @version v1.0
 * @Package com.kabigon.tiny.excel
 * @data 2022/8/10 1:38
 */
@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
    private static final int BATCH_COUNT = 100;
    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("03", Optional.ofNullable(data.get(2)).orElse(""));
        log.info("json: {}", jsonObject.toJSONString());
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 数据库存储
     */
    private void saveData() {
        int xx= 1/0;
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        log.info("存储数据库成功");
    }

}
